package com.lagou.api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class CreateNode implements Watcher {

    private static ZooKeeper zooKeeper;

    /**
     * 创建会话
     *
     * @param args
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        /*
             客户端可以通过创建一个zk实例来连接zk服务器
             new Zookeeper(connectString,sesssionTimeOut,Wather)
             connectString: 连接地址:IP:端口
             sesssionTimeOut:会话超时时间:单位毫秒
             Wather:监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
         */
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNode());

        //线程等待
        Thread.sleep(Integer.MAX_VALUE);
    }

    //当前类实现了Watcher接口，重写了process方法，该方法负责处理来自Zookeeper服务端的 watcher通知，
    // 在收到服务端发送过来的SyncConnected事件之后，解除主程序在CountDownLatch上 的等待阻塞，至此，会话创建完毕
    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("执行了process方法");

            try {
                //创建节点
                createNodeSync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (KeeperException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建节点
     */
    private static void createNodeSync() throws InterruptedException, KeeperException {
        /**
         * path：节点创建的路径
         * data[]: 节点创建要保存的数据，是个byte类型的
         * acl: 节点创建的权限信息(4种类型)
         *      ANYONE_ID_UNSAFE: 表示任何人
         *      OPEN_ACL_UNSAFE: 这是一个完全开放的ACL(常用)-->world:anyone
         *      CREATOR_ALL_ACL: 此ACL授予创建者身份验证ID的所有权限
         * createMode: 创建的节点类型（4种类型）
         *      PERSISTENT：持久节点
         *  	PERSISTENT_SEQUENTIAL：持久顺序节点
         *  	EPHEMERAL：临时节点
         *  	EPHEMERAL_SEQUENTIAL：临时顺序节点
         */
        //持久节点
        String persistent = zooKeeper.create("/la_persistent", "持久节点的内容".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(persistent);
        //持久顺序节点
        String persistent_sequential = zooKeeper.create("/la_persistent_sequential", "持久顺序节点的内容".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        System.out.println(persistent_sequential);
        //临时节点
        String ephemeral = zooKeeper.create("/la_ephemeral", "临时节点的内容".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(ephemeral);
        //临时顺序节点
        String ephemeral_sequential = zooKeeper.create("/la_ephemeral_sequential", "临时顺序节点的内容".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(ephemeral_sequential);
    }
}
